<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\validate\File;
use think\facade\Filesystem;
use think\facade\Validate;

class Tool
{
    /**
     * @title 上传图片
     *
     * @param string $file 文件
     * @param int $type 1图片；2非图片
     *
     * @return string 文件地址
     */
    public function uploadFile()
    {
        $params = request()->only(['file', 'type']);
        $params['file'] = request()->file('file');
        $params['type'] = $params['type'] ?? 1;
        if ($params['type'] == 1) {
            $validate = (new File())->scene('pic');
        } elseif ($params['type'] == 2) {
            $validate = (new File())->scene('file');
        } else {
            result(null, 0, '未知的文件类型');
        }
        if (is_array($params['file'])) {
            foreach ($params['file'] as $file) {
                if ($validate->check(['file' => $file])) {
                    result(null, 0, $validate->getError());
                }
            }
            $saveNameArray = [];
            foreach ($params['file'] as $file) {
                $saveName = Filesystem::putFile('admin', $file);
                $saveNameArray[] = config('extra.app_url') . str_replace('\\', '/', 'uploads/' . $saveName);
            }
            result(['url' => $saveNameArray], 1, '上传成功');
        } else {
            if (!$validate->check($params)) {
                result(null, 0, $validate->getError());
            }
            $saveName = Filesystem::putFile('', $params['file']);
            $url = config('extra.app_url') . str_replace('\\', '/', 'uploads/' . $saveName);
            result(['url' => $url], 1, '上传成功');
        }
    }
}
